<?php

/**
 * This is the model class for table "user".
 */
Yii::import('User.models.base.UserBase');
class User extends UserBase
{
    const STATUS_DEACTIVE = 0, STATUS_ACTIVE = 1;
    const REGISTER_VALIDATION_TYPE = 1, FORGOT_PASSWORD_VALIDATION_TYPE = 2; 
    
    public $confirmPassword;
    public $passwordOld;
    public $verifyCode;
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            // admin user
            array('username, password, email', 'required', 'on'=>'create_admin_user'),
            array('username, email', 'unique', 'on'=>'create_admin_user'),
            array('username, email', 'required', 'on'=>'update_admin_user'),
            array('username', 'usernameExists', 'on'=>'update_admin_user'),
            array('email', 'emailExists', 'on'=>'update_admin_user'),
            // forgot password
            array('email', 'required', 'on'=>'forgot_password'), 
            
            array('password, email', 'required', 'on'=>'register, login'),
            array('password', 'required', 'on'=>'reset, change_password'),
            
            array('username', 'required', 'on'=>'register'),
            array('username, email', 'unique', 'on'=>'register'),
            array('email', 'email', 'on'=>'register, login, create_admin_user, update_admin_user, forgot_password'),
            //array('username', 'filter', 'filter'=>'strtolower', 'on'=>'register'),
            array('username', 'match', 'pattern'=>'/^[a-zA-Z0-9_]{5,50}$/', 'on'=>'register, create_admin_user, update_admin_user'),
            array('password', 'length', 'min'=>5),
            array('confirmPassword', 'compare', 'compareAttribute' => 'password', 'on'=>'register, reset, change_password, create_admin_user, update_admin_user'),
            array('email', 'required', 'on'=>'forgot'),   
            array('verifyCode', 'required', 'on'=>'forgot_confirm'),   
            array('email', 'exist', 'on'=>'forgot'),
            array('passwordOld', 'required', 'on'=>'change_password'),
            
            array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(), 'on'=>'forgot_confirm'),
            
            array('validation_code, validation_type, validation_expired, status, created_date, last_login', 'safe'),
            array('id, username, password, email, created_date, last_login, validation_code, validation_type, validation_expired, status', 'safe', 'on'=>'search'),
        );
    }
    
    public function usernameExists($attribute, $params) {
        if (!$this->hasErrors($attribute))
        {
            $user = self::model()->findByAttributes(array('username' => $this->username));
            if (!is_null($user) && $user->id != $this->id)
            {
                $this->addError('username', 'Sorry! This Username existed.');
                return false;
            }
        }
    }

    /**
     * @desc Check if email already exists
     */
    public function emailExists($attribute, $params) {
        if (!$this->hasErrors($attribute))
        {
            $user = self::model()->findByAttributes(array('email' => $this->email));
            if (!is_null($user) && $user->id != $this->id){
                $this->addError('email', 'Sorry! This email existed.');
                return false;
            }
        }
    }
    
    public function getStatusOptions()
    {
        return array(
            self::STATUS_DEACTIVE => 'Deactive',
            self::STATUS_ACTIVE => 'Active',
        );
    }
    
    public function getStatusText()
    {
        $options = $this->getStatusOptions();
        return isset($options[$this->status]) ? $options[$this->status] : Yii::t('app', 'Unknown {att}', array('{att}'=>$this->status));
    }

    /**
     * This method is invoked after saving a record successfully.
     * The default implementation raises the {@link onAfterSave} event.
     * You may override this method to do postprocessing after record saving.
     * Make sure you call the parent implementation so that the event is raised properly.
     */
    protected function beforeSave()
    {
        
        if ($this->getIsNewRecord()) {
            $this->created_date = date('Y-m-d H:i:s');
            if (!isset($this->status))
                $this->status = self::STATUS_ACTIVE;
        }
        return parent::beforeSave();
    }
    
    /**
     * This method is invoked before validation starts.
     * The default implementation calls {@link onBeforeValidate} to raise an event.
     * You may override this method to do preliminary checks before validation.
     * Make sure the parent implementation is invoked so that the event can be raised.
     * @return boolean whether validation should be executed. Defaults to true.
     * If false is returned, the validation will stop and the model is considered invalid.
     */
    protected function beforeValidate()
    {
        $this->username = strtolower($this->username);
        return parent::beforeValidate();
    }
    
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        'profile'=>array(self::HAS_ONE,'UserProfile','user_id'),
        );
    }
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'confirmPassword'=>'Confirm Password',
            'email' => 'Email',
            'created_date' => 'Created Date',
            'last_login' => 'Last Login',
            'validation_code' => 'Validation Code',
            'validation_type' => 'Validation Type',
            'validation_expired' => 'Validation Expired',
            'status' => 'Status',
            'verifyCode'=>'Verify Code',
        );
    }
}